package cn.edu.zime.tjh.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.function.Consumer;

public class AsyncClientHandler extends ChannelInboundHandlerAdapter {
    private Consumer<String> messageCallback;
    private Consumer<String> statusCallback;
    
    public AsyncClientHandler(Consumer<String> messageCallback, Consumer<String> statusCallback) {
        this.messageCallback = messageCallback;
        this.statusCallback = statusCallback;
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (statusCallback != null) {
            statusCallback.accept("Connected to server: " + ctx.channel().remoteAddress());
        }
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String message = (String) msg;
        
        if (messageCallback != null) {
            // 根据消息类型进行分类处理
            if (message.startsWith("[Server Broadcast]:")) {
                messageCallback.accept("BROADCAST|" + message.substring("[Server Broadcast]: ".length()));
            } else if (message.startsWith("[Server Message]:")) {
                messageCallback.accept("SERVER|" + message.substring("[Server Message]: ".length()));
            } else {
                messageCallback.accept("ECHO|" + message);
            }
        }
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        if (statusCallback != null) {
            statusCallback.accept("Disconnected from server");
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (statusCallback != null) {
            statusCallback.accept("Error: " + cause.getMessage());
        }
        ctx.close();
    }
}